package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * FileController  TODO
 * 13418  computer
 *
 * @author zhougang
 * @date 2020/3/26 15:13
 */

@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file){
        try {
            //判断文件存在
            if (file == null){
                throw new RuntimeException("文件不存在");
            }
            //获取文件名称
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)){
                throw new RuntimeException("文件不存在");
            }
            //获取文件扩展名
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //获取文件内容
            byte[] content = file.getBytes();
            //创建用于文件上传的封装实体类
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, content, extName);
            //通过工具类实现文件上传,并获取返回参数
            String[] uploadResult = FastDFSClient.upload(fastDFSFile);
            //封装结果对象
            String url = FastDFSClient.getTrackerUrl() + uploadResult[0] + "/" + uploadResult[1];
            return new Result(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR, "文件上传失败");
    }

    @DeleteMapping("/del")
    public Result deleteFile(String url) throws Exception {
        try {
            Integer i = FastDFSClient.deleteFile1(url);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("删除失败");
        }
        return new Result();
    }

}
